import IdiomWords from './data'
import pinyin from 'pinyin'

const IdiomLengthArr = [4, 7, 9] // 合法字数
const medalArr = ['🥇', '🥈', '🥉', '🍭', '🍭', '🍭', '🍭', '🍭', '🍭', '🍭'] // 奖牌数量

export default class IdiomSolitailre {
  constructor () {
    this.usedWords = [] // 已用词
    this.status = 0 // 1为游戏状态
    this.word = '' // 当前词
    this.players = [] // 参与玩家 { name: 'xxx', score: 1}
    this.count = 0 // 当前词数
    this.last = '' // 最后一个文字的音
    this.minuteId = null // 一分钟定时器
    this.counterId = null // 40s定时器
    this.totalLength = IdiomWords.length
  }
  init ({bot, msg, currentContact}) {
    const wordObj = this.getRandomWord()
    this.status = 1
    this.changeCurrentWord(bot, msg, wordObj, currentContact, true)
  }
  run ({bot, msg, currentContact, content}) {
    let returnMsg = ''
    const playerName = currentContact.NickName
    const currentWord = IdiomWords.find(item => {
      return item.word === content
    })
    // 异常情况处理
    if (content.startsWith('结束')) {
      this.reset(bot, msg)
      return
    }

    // 如果不是合法直接返回(该拼音开头但是字数不对或不在词库)
    const last = pinyin(content[0], { style: pinyin.STYLE_NORMAL }).join('')
    if (last !== this.last) return
    if (!IdiomLengthArr.includes(content.length) || !currentWord) {
      bot.sendMsg(`☝ 【${content}】这不是成语哦。`, msg.FromUserName)
      return
    }

    if (this.usedWords.includes(content)) {
      returnMsg = `${content}已经说过了！`
      bot.sendMsg(returnMsg, msg.FromUserName)
      return
    }

    let currentPlayer = this.players.find(item => {
      return item.name === playerName
    })
    if (!currentPlayer) {
      currentPlayer = { name: playerName, score: 1 }
      this.players.push(currentPlayer)
    } else {
      currentPlayer.score++
    }

    this.changeCurrentWord(bot, msg, currentWord, currentContact, false)
    if (this.count > 10) {
      this.reset(bot, msg)
    }
  }

  reset (bot, msg) {
    let gradeStr = ''; let sendTxt = ''
    this.players.sort((a, b) => b.score - a.score)
    this.players.forEach((player, index) => {
      gradeStr += `${medalArr[index]} 第${index + 1}名：@${player.name}  （接龙${player.score}次）\n`
    })

    if (this.players.length === 0) {
      sendTxt = '游戏结束，现在公布成绩\n没有人接龙成功😱😱'
    } else {
      sendTxt = `游戏结束，现在公布成绩：\n\n ${gradeStr}\n`
    }
    if (this.minuteId) clearTimeout(this.minuteId)
    if (this.counterId) clearTimeout(this.counterId)
    bot.sendMsg(sendTxt, msg.FromUserName)
    bot.emit('exitGame', msg.FromUserName)
  }

  getRandomWord () {
    const index = Math.floor(Math.random() * this.totalLength)
    return IdiomWords[index]
  }
    
  refreshTimer (bot, msg) {
    if (this.minuteId) clearTimeout(this.minuteId)
    if (this.counterId) clearTimeout(this.counterId)
    this.counterId = setTimeout(() => { bot.sendMsg('⚡ 还剩20秒！', msg.FromUserName) }, 40000)
    this.minuteId = setTimeout(() => { this.reset(bot, msg) }, 60000)
  }

  changeCurrentWord (bot, msg, wordObj, currentContact, isFirst = false) {
    let returnMsg = ''
    this.count++
    this.word = wordObj.word
    this.last = pinyin(wordObj.word.slice(-1), { style: pinyin.STYLE_NORMAL }).join('')
    this.usedWords.push(wordObj.word)
    // 是否是首次
    if (isFirst) {
      bot.sendMsg('‼成语接龙规则：直到接满10条或者无法再继续则游戏结束。每次接龙时间为⏱1分钟。可以同音字接龙！', msg.FromUserName)
      returnMsg = `第${this.count}个成语：👉${wordObj.word}👈`
    } else {
      bot.sendMsg(`🎊 恭喜 @${currentContact.NickName}  接龙成功！`, msg.FromUserName)
      returnMsg = `第${this.count}个成语：👉${wordObj.word}👈`
    }
    this.refreshTimer(bot, msg)
    if (this.count > 10) return
    bot.sendMsg(returnMsg, msg.FromUserName)
  }
}

